<?php

namespace app\store\job;

use think\facade\Db;
use think\queue\Job;

class Account
{
    /**
     * 积分队列
     * */
    public function integral(Job $job, $data)
    {
        if ($job->attempts()>3){
            $job->delete();
        }


        Db::startTrans();
        try {
            $query = Db::name('user')
                ->where('user_id',$data['user_id']);

            if ($data['change_type']==1){
                $query->inc('integral',$data['integral']);
            }

            if ($data['change_type']==2){
                $query->dec('integral',$data['integral']);
            }

            $query->update();

            $result = Db::name('user_integral_detail')->insert([
                'user_id' => $data['user_id'],
                'change_desc' => $data['desc'],
                'change_type' => $data['change_type'],
                'change_integral' => $data['integral'],
                'change_time' => time(),
            ]);
            Db::commit();

            if ($result){
                $job->delete();
            }
        }catch (\Exception $e){
            Db::rollback();
            if ($job->attempts()>2){
                $job->delete();
            }
        }


    }

    /**
     * 余额队列
     * */
    public function balance(Job $job, $data){

        Db::startTrans();
        try {
            $query = Db::name('user')
                        ->where('user_id',$data['user_id']);

            if ($data['change_type']==1){
                $query->inc('balance',$data['balance']);
            }

            if ($data['change_type']==2){
                $query->dec('balance',$data['balance']);
            }

            $query->update();

            $result = Db::name('user_balance_detail')->insert([
                'user_id' => $data['user_id'],
                'change_desc' => $data['desc'],
                'change_type' => $data['change_type'],
                'change_balance' => $data['balance'],
                'change_time' => time(),
            ]);
            Db::commit();
            if ($result){
                $job->delete();
            }
        }catch (\Exception $e){
            Db::rollback();
            if ($job->attempts()>2){
                $job->delete();
            }
        }
    }
}